<template>
  <backContainer :type="paperType" :closeState.sync="closeState">
    <AnswerPaperComponent
      :examInfo="examInfo"
      :topicTotalNum="topicTotalNum"
      :endTime="endTime"
      :loading="loading"
      :paperType="paperType"
      :componentType="componentType"
      @submitSingleAnswer="submitSingleAnswer"
      @finshAnswerPaper="finshAnswerPaper"
    >
    </AnswerPaperComponent>
  </backContainer>
</template>

<script>
import AnswerPaperComponent from './components/AnswerPaperComponent'
import { recordStudyTime } from "@/api/course/course";
import { returnType, returnName } from "@/utils/util";
import { startExamApi,finshExamPaperApi,submitSingleAnswerApi } from '@/api/ExaminationModule/exam'

export default {
  name: "answerExam",
  components: {
    AnswerPaperComponent
  },
  data() {
    return {
      paperTypeText: {
        1: '考核',
        3: '练习',
        6: '作业'
      },
      paperType:1,
      componentType:'start',
      // 用于记录的步骤时间
      studyStartTime: null,
      studyRecordId: "",
      examInfo: {},
      topicTotalNum:0,
      loading: false,
      closeState: false,
      endTime: "",
    };
  },
  created() {
    this.studyRecordId = this.$route.query.studyRecordId;
    this.paperType = this.$route.query.type-0;
    this.getExaminationAnswerList();
  },
  beforeDestroy() {
    if (this.studyStartTime) {
      let studyTimeData = (new Date().getTime() - this.studyStartTime) / 1000;
      recordStudyTime(this.studyRecordId, Math.ceil(studyTimeData)).then(
        (res) => {
          if (res.code == 200) {
            console.log("记录学习时间:", studyTimeData);
            this.studyStartTime = null;
          }
        }
      );
    }
  },
  methods: {
    async submitSingleAnswer(obj) {
      try {
        let res = await submitSingleAnswerApi(obj);
        const { code } = res;
        if (code == 200) {
          console.log('保存成功')
        }
      } catch (e) {
        console.error(e);
      }
    },
    /**
     * 如果需要则记录学习时间
     */
    async recordStudyTimeIfNeeded() {
      if (!this.studyStartTime) return;

      const studyTimeData = Math.ceil((new Date().getTime() - this.studyStartTime) / 1000);
      const res = await recordStudyTime(this.studyRecordId, studyTimeData);
      if (res.code === 200) {
        console.log("记录学习时间:", studyTimeData);
        this.studyStartTime = null;
      }
    },
    /**
     * 跳转到考试详情页
     */
    navigateToExamDetail() {
      this.$router.replace({
        path: "/examDetail",
        query: {
          type: this.$route.query.type,
          id: this.examInfo.id,
        },
      });
    },
    async finshAnswerPaper(id) {
      const loading = this.$loading({
        lock: true,
        text: "正在提交…",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      try {
        let res = await finshExamPaperApi(id);
        const {code,data} = res
        if (code == 200) {
          if (data==-2){
            this.$modal.msgWarning(`课程已更新，该${this.paperTypeText[this.paperType]}不存在`)
            this.$router.go(-1)
          }else {
            this.recordStudyTimeIfNeeded()
            this.navigateToExamDetail()
          }
        }
      } catch (error) {
        console.error(error);
      }finally {
        loading.close();
      }
    },
    async getExaminationAnswerList() {
      this.loading = true;
      try {
        let res = await startExamApi(this.$route.query.id,this.$store.getters.studentId, this.studyRecordId);
        const {code,data} = res
        if (code==200){
          //通过finishTime来判断是否需要记录学习时间
          if (!data.finishTime) {
            this.studyStartTime = new Date().getTime();
          } else {
            this.studyStartTime = null;
          }
          data.taskInfo = data.title
          let formatData = this.formatDataInfo(data);
          this.examInfo = formatData.formatObj
          this.topicTotalNum = formatData.topicTotalNum
          if (data.finishTime || (!data.finishTime && !data.isLimitedTime) ) {
            this.closeState = true;
          }
          const userAgent = navigator.userAgent.toLowerCase();
          //判断是苹果浏览器 safari
          let endtime;
          if (userAgent.includes("safari") && !userAgent.includes("chrome")) {
            endtime = data.endTime.replace(/-/g, "/");
          } else {
            endtime = data.endTime;
          }
          this.endTime = new Date(endtime).getTime() + "";
        }

      } catch (e) {
        if (e.message.includes("未开始学习")) {
          this.$router.go(-1);
        }
      } finally {
        this.loading = false;
      }
    },
    /**
     * 格式化考试数据
     * @param {Object} data - 原始考试数据
     * @returns {Object} 包含格式化后的数据(formatObj)和试题总数(topicTotalNum)
     */
    formatDataInfo(data) {
      // 计算试题总数
      const topicTotalNum = data.examPaperTitleList.reduce(
        (total, paperElement) => total + paperElement.topicNum, 0
      );
      // 处理每个大题
      const formatTitleList = data.examPaperTitleList.map(paperElement => {
        // 处理每个小题
        const topicList = paperElement.topicList.map(topicElement => {
          // 初始化基础对象
          const baseObj = {
            ...topicElement,
            userAnswer: "",
            multiAnswers: [],
            echoFile: [],
            settlePic: topicElement.settlePic ? topicElement.settlePic.split(",") : [],
            showDialogState: false,
            showCameraDialog: false
          };
          // 处理有答案的情况
          if (topicElement.topicAnswer) {
            // 处理选择题选项状态
            if ([0, 1].includes(topicElement.topicType)) {
              topicElement.topicOptionList.forEach(item => {
                item.isChecked = topicElement.topicAnswer.answer == item.label || (topicElement.topicAnswer.multiAnswers || []).includes(item.label);
              });
            }
            // 更新答案相关字段
            const answerObj = {
              userAnswer: topicElement.topicAnswer.answer || "",
              multiAnswers: topicElement.topicAnswer.multiAnswers || []
            };
            // 处理文件信息
            if (topicElement.topicAnswer.fileInfo) {
              answerObj.echoFile = JSON.parse(topicElement.topicAnswer.fileInfo).map(file => {
                if (file.url) {
                  return {
                    ...file,
                    type: returnType(file.url),
                    name: file.name ? file.name : returnName(file.url)
                  };
                }
                return file;
              });
            }
            Object.assign(baseObj, answerObj);
          } else if ([0, 1].includes(topicElement.topicType)) {
            // 初始化未作答的选择题选项状态
            topicElement.topicOptionList.forEach(item => {
              item.isChecked = false;
            });
          }
          return baseObj;
        });
        return {
          ...paperElement,
          topicList
        };
      });
      // 构建最终返回对象
      const formatObj = {
        ...data,
        examPaperTitleList: formatTitleList,
        finishTime: [1, -1, 3].includes(data.passing)
      };
      return { formatObj, topicTotalNum };
    }
  },
};
</script>

<style scoped lang="scss">
//富文本回显样式
::v-deep h5,
.h5 {
  font-size: 14px;
}

::v-deep h4,
.h4 {
  font-size: 16px;
  font-weight: bold;
}

::v-deep h3,
.h3 {
  font-size: 18px;
  font-weight: bold;
}

::v-deep h2,
.h2 {
  font-size: 20px;
  font-weight: bold;
}

::v-deep h1,
.h1 {
  font-size: 22px;
  font-weight: bold;
}
::v-deep i {
  font-style: italic;
}
::v-deep .w-e-toolbar .w-e-menu i {
  font-style: normal;
}
::v-deep ol {
  list-style-type: decimal;
}

/* ul ol 样式 */
::v-deep ol {
  margin: 10px 0 10px 22px;
  list-style-type: decimal;
}
::v-deep ul {
  margin: 10px 0 10px 22px;
  list-style-type: disc;
}
/* table 样式 */
::v-deep table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
::v-deep table td,
::v-deep table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
  height: 32px;
}
::v-deep table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
  background-color: #f1f1f1;
}

/* blockquote 样式 */
::v-deep blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  min-height: 24px;
  font-size: 100%;
  background-color: #f1f1f1;
}

/* code 样式 */
::v-deep code {
  display: inline-block;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}
::v-deep pre code {
  display: block;
}
::v-deep a {
  text-decoration: underline;
  color: #5592e5;
}
::v-deep .el-icon-plus{
  font-style: normal!important;
}
::v-deep .el-icon-document{
  font-style: normal!important;
}
::v-deep .el-icon-circle-close{
  font-style: normal!important;
}
</style>
